<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Redmanagement_model extends CI_Model {
	
	function __construct(){
        parent::__construct();
    }
    
    function update($id,$data){
    	$this->db->where('id', $id);
		$this->db->update('rsh_redmanagement', $data);
		return $this->db->affected_rows();
    }
    
 	function get_list(){
    	$query = $this->db->query("select * from rsh_redmanagement");
    	return $query->result_array();
    }
    
	function getobj($id){
    	$query = $this->db->query("select * from rsh_redmanagement where id=$id");
    	return $query->row_array();
    }
    
    function send_red($user_id,$type,$remark='发放代金券',$money = 0){
    	$this->load->model('Account_model', 'redaccount');
		$redObj = self::getobj($type);
		if($redObj['fstatus'] == 1 && $redObj['start_time']<time() && $redObj['end_time']>time()){
			$res =  $this->redaccount->is_accountlog(array("user_id"=>$user_id,"remark"=>$remark));	//判断是否发过此类代金卷
			if($res || $redObj['money'] < 0){
				$red_account_result =  $this->redaccount->get_account($user_id);	
				if(!$red_account_result['total']){
					$initAccount = array('user_id'  => $user_id,'total'=> '0','use_money'=>'0','no_use_money' =>'0','collection'=> '0','red_money'=>'0');
					$account_id = $this->redaccount->init_account($initAccount);
				}
				$red_account_result 	=  $this->redaccount->get_account($user_id);
				$redlog['user_id'] 		= $user_id;
				$redlog['ftype'] 		= REDPACKAGE;
				if($redObj['money'] < 0) $redObj['money'] = $money;//如果设置金额为负数，说明赠送金额自定义
				$redlog['money'] 		= $redObj['money'];
				$redlog['total'] 		= $red_account_result['total'];
				$redlog['use_money'] 	= $red_account_result['use_money'];
				$redlog['no_use_money'] = $red_account_result['no_use_money'];
				$redlog['collection'] 	= $red_account_result['collection'];
				$redlog['red_money'] =  $red_account_result['red_money'] + $redObj['money'];
				$redlog['to_user'] 		= 0;
				$redlog['add_time'] 	= time();
				$redlog['addip'] 		= '127.0.0.1';
				$redlog['remark'] 		= $remark;
				$this->redaccount->accountlog($redlog);
				
				$this->load->model ( 'Systemtemplet_model', 'system' );//收到红包发送站内信
				$obj = $this->system->get_templet_obj(24);
				if ($obj && $user_id > 0) {
					$this->load->model ( 'User_model', 'user' );
					$minfo = $this->user->get_by_uid ( $user_id );
					$templetBody = $obj ['content'];
					$msgBody = str_replace ( array('#username#','#money#'),array($minfo['username'],$redObj['money']), $templetBody);
					$this->load->model ( 'Message_model', 'message' );
					$msg = array ('sent_user' => 1, 'receive_user' => $user_id, 'name' => $obj['title'], 'fstatus' => 0, 'message_type' => 'system', 'sented' => 0, 'deltype' => 0, 'content' => $msgBody, 'add_time' => time (), 'addip' => $this->input->ip_address () );
					$this->message->send ( $msg );
				}
			}
		}
    }
}